const db = require("./db");

function User(user) {
    this.id = user.id;
    this.username = user.username;
    this.password = user.password;
    this.mobile = user.mobile;
    this.isDelete = user.isDelete;
}
User.queryUser = (page, callback) => {
    let selectSql = "select * from user";
    selectSql += " limit ?,?";
    db.query(selectSql, [(page.page - 1) * page.size, page.size], (err, result) => {
        if (err) return callback(err);
        let data = result;
        callback(err, data);
    })
}
User.addUser = (user, callback) => {
    let selectSql = "insert into user (id, username, password, mobile, isDelete) values (null,?,?,?,?)";
    db.query(selectSql, [user.username, user.password, user.mobile, user.isDelete], (err, result) => {
        if (err) return callback(err);
        callback(err, result);
    })
}
User.queryUserMessage = (id, callback) => {
    let selectSql = "select * from user where id=?";
    db.query(selectSql, [id], (err, result) => {
        if (err) return callback(err);
        let data = result[0];
        callback(err, data);
    })
}
User.countUser = (callback) => {
    let selectSql = "select count(id) as count from user";
    db.query(selectSql, (err, result) => {
        if (err) return callback(err);
        let data = result[0];
        callback(err, data);
    })
}
User.updatePassword = (id, password, callback) => {
    let selectSql = "update user set password = ? where id= ?";
    db.query(selectSql, [password, id], (err, result) => {
        if (err) return callback(err);
        callback(err, result);
    })
}
User.updateUser = (user, callback) => {
    let selectSql = "update user set isDelete = ? where id=?";
    db.query(selectSql, [parseInt(user.isDelete), user.id], (err, result) => {
        if (err) return callback(err);
        callback(err, result);
    });
}
User.getUserById = (id, callback) => {
    let selectSql = "select * from user where id=?";
    db.query(selectSql, [id], (err, result) => {
        if (err) return callback(err);
        let data = result[0];
        callback(err, data);
    })
}
User.getUserByName = (username, callback) => {
    let selectSql = 'select * from user where username = ?';
    db.query(selectSql, [username], (err, result) => {
        if (err) {
            return callback(err);
        }
        let data = result;
        callback(err, data);
    });
};
User.getUserByMobile = (mobile, callback) => {
    let selectSql = 'select * from user where mobile = ?';
    db.query(selectSql, [mobile], (err, result) => {
        if (err) return callback(err);
        let data = result;
        callback(err, data);
    });
};

module.exports = User;